package es.mgil.whoWantsToBeAMillonaire.activities;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;

import es.mgil.whoWantsToBeAMillonaire.R;
import es.mgil.whoWantsToBeAMillonaire.runnables.GetFriendsScoresRunnable;
import es.mgil.whoWantsToBeAMillonaire.util.MillonaireDatabaseHelper;
import es.mgil.whoWantsToBeAMillonaire.util.PreferencesKeys;
import es.mgil.whoWantsToBeAMillonaire.util.ScoreRow;
import es.mgil.whoWantsToBeAMillonaire.views.ExtendedMapView;

public class Scores extends MapActivity implements OnTabChangeListener {
	public static final String LocalTab = "LocalTab";
	public static final String FriendsTab = "FriendsTab";

	private ExtendedMapView map;
	private TableLayout tableLocal;
	private TabHost tabHost;

	private SharedPreferences preferences;
	private Editor editor;

	private boolean localLoaded = false;
	private boolean mapLoaded = false;

	private MillonaireDatabaseHelper dbHelper;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.layout_scores);

		// store the preferences
		preferences = getSharedPreferences(PreferencesKeys.SHARED_PREFERENCES,
				MODE_PRIVATE);
		editor = preferences.edit();

		// get a database helper
		dbHelper = new MillonaireDatabaseHelper(this);

		// initialize some useful objects from interface
		tableLocal = (TableLayout) findViewById(R.id.tabLocal);

		map = (ExtendedMapView) findViewById(R.id.map);
		map.setBuiltInZoomControls(true);

		tabHost = (TabHost) findViewById(R.id.tabHostScores);
		tabHost.setup();
		tabHost.setOnTabChangedListener(this);

		TabSpec spec1 = tabHost.newTabSpec(LocalTab);
		spec1.setIndicator(getResources().getText(R.string.score_Tab1));
		spec1.setContent(R.id.tabLocal);
		tabHost.addTab(spec1);

		TabSpec spec2 = tabHost.newTabSpec(FriendsTab);
		spec2.setIndicator(getResources().getText(R.string.score_Tab2));
		spec2.setContent(R.id.tabFriends);
		tabHost.addTab(spec2);

		// restart the current selected tab
		tabHost.setCurrentTabByTag(preferences.getString(
				PreferencesKeys.PREFERENCES_CURRENT_TAB, LocalTab));
	}

	@Override
	protected void onPause() {
		// store the current selected tab
		editor.putString(PreferencesKeys.PREFERENCES_CURRENT_TAB,
				tabHost.getCurrentTabTag());
		editor.commit();

		super.onPause();
	}

	@Override
	public void finish() {
		// closes the database if opened
		dbHelper.close();

		super.finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_scores, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// only show the menu if local tab is the current
		if (tabHost.getCurrentTabTag().equals(LocalTab)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_deleteLocalScores:
			deleteLocalScores();
			return true;
		default:
			return super.onMenuItemSelected(featureId, item);
		}
	}

	@Override
	public void onTabChanged(String tabId) {
		// force to load data only once for every tab
		if (LocalTab.equals(tabId)) {
			if (!localLoaded) {
				refreshTabLocal();
				localLoaded = true;
			}
		} else if (FriendsTab.equals(tabId)) {
			if (!mapLoaded) {
				refreshTabMap();
				mapLoaded = true;
			}
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	/**
	 * Delete all local scores
	 */
	private void deleteLocalScores() {
		dbHelper.deleteLocalScores();
		Toast.makeText(this, R.string.score_delete_ok, Toast.LENGTH_LONG)
				.show();
		refreshTabLocal();
	}

	/**
	 * Refresh the tab for local scores
	 */
	private void refreshTabLocal() {
		// first remove all rows
		tableLocal.removeAllViews();

		// then create it from the rows in the local database
		for (ScoreRow sr : dbHelper.getLocalScores()) {
			TableRow row = new TableRow(this);

			TextView name = new TextView(this);
			name.setText(sr.name);
			name.setGravity(Gravity.LEFT);
			row.addView(name);

			TextView localization = new TextView(this);
			localization.setText(sr.address);
			localization.setGravity(Gravity.CENTER);
			row.addView(localization);

			TextView points = new TextView(this);
			points.setText(String.valueOf(sr.score));
			points.setGravity(Gravity.RIGHT);
			row.addView(points);

			tableLocal.addView(row);
		}
	}

	/**
	 * Refresh the tab for map friends scores
	 */
	private void refreshTabMap() {
		// retrieve the name stored in preferences (from Settings activity)
		String name = preferences.getString(PreferencesKeys.PREFERENCES_NAME,
				"");

		// launch a runnable to get all scores friends
		new GetFriendsScoresRunnable(this, name).loadFriendsScores();

		// locate my position in the map and reveal it
		double longitude = preferences.getFloat(
				PreferencesKeys.PREFERENCES_LONGITUDE, 0);
		double latitude = preferences.getFloat(
				PreferencesKeys.PREFERENCES_LATITUDE, 0);
		GeoPoint point = new GeoPoint((int) (latitude * 1e6),
				(int) (longitude * 1e6));
		MapController mapController = map.getController();
		mapController.setZoom(17);
		mapController.animateTo(point);
	}

	/**
	 * Return the map view
	 */
	public ExtendedMapView getMapView() {
		return map;
	}
}
